package com.vanzo.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.widget.TextView;

import com.vanzo.bean.Follower;
import com.vanzo.bean.Master;
import com.vanzo.encryption.Encryption;
import com.vanzo.encryption.R;
import com.vanzo.nfc.NFCManager;
import com.vanzo.service.PowerReceiver;
import com.vanzo.service.PttKeyReceiver;
import com.vanzo.service.Talkie;
import com.vanzo.util.LogUtil;

import java.util.ArrayList;

/**
 * Created by tisen on 2017/12/25.
 */

public class HomeActivity extends BaseActivity implements TalkieFragment2.BindNFC {

    public static final String TAG = "HomeActivity";


    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private TalkieFragment2 talkieFragment2;
    private ContactFragment contactFragment;
    private ChatListFragment chatListFragment;
    private SettingFragment2 settingFragment2;

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ArrayList<TabLayout.Tab> tabs = new ArrayList<>();

    private NFCManager nfcManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (tpplication.getMaster() == null) {
            initMaster();
        }
        nfcManager = new NFCManager(this);
        setContentView(R.layout.activity_home);
        initView();
        initData();
        instruction.setPower(true);
    }

    private void initMaster() {
        Master master = new Master();
        master.setIsMaster(true);
        master.setGk(Encryption.getGroupKey());
        tpplication.updateMaster(master);
    }


    protected void initView() {
        tabLayout = (TabLayout) findViewById(R.id.home_fragment_tab);
        viewPager = (ViewPager) findViewById(R.id.home_fragment_viewPager);
    }

    protected void initData() {
        tabs.add(tabLayout.newTab().setText("0"));
        tabs.add(tabLayout.newTab().setText("1"));
        tabs.add(tabLayout.newTab().setText("2"));
        tabs.add(tabLayout.newTab().setText("3"));

        talkieFragment2 = new TalkieFragment2();
        contactFragment = new ContactFragment();
        //contactFragment = new TalkieFragment();
        //chatListFragment = new TalkieFragment();
        //settingFragment2 = new TalkieFragment();
        chatListFragment = new ChatListFragment();
        settingFragment2 = new SettingFragment2();

        fragments.add(contactFragment);
        fragments.add(talkieFragment2);
        fragments.add(chatListFragment);
        fragments.add(settingFragment2);

        talkieFragment2.setBindNFC(this);

        adapter = new ViewPagerAdapter(getFragmentManager(), tabs, fragments, this);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(1);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        tabLayout.getTabAt(0).setCustomView(R.layout.bottom_item_contact);
        tabLayout.getTabAt(1).setCustomView(R.layout.bottom_item_talkie);
        tabLayout.getTabAt(2).setCustomView(R.layout.bottom_item_message);
        tabLayout.getTabAt(3).setCustomView(R.layout.bottom_item_setting);
        initWakeAndReceiver();
        nfcManager = new NFCManager(this);
        nfcManager.setCallback(null, createNdefMessageCallback, onNdefPushCompleteCallback);
    }

    private boolean isBinding = false;

    @Override
    protected void onResume() {
        super.onResume();
        try {
            nfcManager.verifyNFC();
            if (isBinding) {
                nfcManager.startBind();
            } else {
                nfcManager.stopBind();
            }
        } catch (NFCManager.NFCNotSupported nfcNotSupported) {
            nfcNotSupported.printStackTrace();
        } catch (NFCManager.NFCNotEnabled nfcNotEnabled) {
            nfcNotEnabled.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private NfcAdapter.CreateNdefMessageCallback createNdefMessageCallback = new NfcAdapter.CreateNdefMessageCallback() {
        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            Master master = tpplication.getMaster();
            byte[] nfc;
            nfc = Encryption.getNfc2(master, theNeedBindOne);
            LogUtil.put(this, "nfc length = " + nfc.length, LogUtil.WARN);
            return nfcManager.createTextMessage(nfc, nfc.length);
        }
    };

    private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback = new NfcAdapter.OnNdefPushCompleteCallback() {
        @Override
        public void onNdefPushComplete(NfcEvent event) {
            stopBind();
        }
    };
    private Dialog dialogTitle;

    private void startBind() {
        isBinding = true;
        nfcManager.startBind();
        dialogTitle = new Dialog(this);
        dialogTitle.setTitle("绑定终端用户:" + theNeedBindOne.getTerminalId());
        TextView textView = new TextView(this);
        textView.setText("请将手机背靠另一台设备");
        dialogTitle.setContentView(textView);
        dialogTitle.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                stopBind();
            }
        });
        dialogTitle.show();
    }

    private void stopBind() {
        if (dialogTitle != null) {
            dialogTitle.dismiss();
        }
//        theNeedBindOne = null;
        isBinding = false;
        nfcManager.stopBind();
    }

    private Handler refreshView = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            talkieFragment2.refreshFollower();
        }
    };

    private void bindNFC(Encryption.NFC nfc) {
        Master master = tpplication.getMaster();
        master.setChannelId(nfc.getChannelId());
        master.setFirstId(nfc.getFirstTid());
        master.setFollowerSize(nfc.getTotalTerminalSize());
        master.setTerminalId(nfc.getTerminalId());
        master.setGroupId(nfc.getGroupId());
        master.setLocked(nfc.getIsLocked() == 1);
        master.setIsMaster(false);

        tpplication.bindMaster(master);
        refreshView.sendEmptyMessage(0);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        nfc = nfcManager.readBinaryFromTag(intent);
        nfcBindHandler.sendEmptyMessage(0);
    }

    private Encryption.NFC nfc;
    private Handler nfcBindHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (nfc != null) {
                AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
                builder.setTitle("绑定此主用户");
                builder.setMessage("组号:" + nfc.getGroupId() + " | 终端号:" + nfc.getTerminalId());
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bindNFC(nfc);
                    }
                });
                builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        }
    };

    private Follower theNeedBindOne;

    @Override
    public void onBindNFC(int position) {
        theNeedBindOne = tpplication.getFollowers().get(position);
//        startBind();
    }

    private PttKeyReceiver pttKeyReceiver;
    private PowerReceiver powerReceiver;
    private IntentFilter pttKeyFilter;
    private IntentFilter powerFilter;
    private PowerManager powerManager;
    private PowerManager.WakeLock wakeLock;

    private void initWakeAndReceiver() {
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

        pttKeyReceiver = new PttKeyReceiver();
        pttKeyReceiver.setListener(listener);
        pttKeyFilter = new IntentFilter();
        pttKeyFilter.addAction(PttKeyReceiver.ACTION_PTT_DOWN);
        pttKeyFilter.addAction(PttKeyReceiver.ACTION_PTT_UP);

        powerReceiver = new PowerReceiver();
        powerFilter = new IntentFilter();
        powerFilter.addAction(PowerReceiver.ACTION_POWER_OFF);
        powerFilter.addAction(PowerReceiver.ACTION_POWER_ON);
        startReceiver();
    }

    private PttKeyReceiver.OnKeyListener listener = new PttKeyReceiver.OnKeyListener() {
        @Override
        public void onKeyListener(String action) {
            talkieFragment2.setAction(action);
        }
    };

    private void startReceiver() {
        wakeLock.acquire();
        registerReceiver(pttKeyReceiver, pttKeyFilter);
//        registerReceiver(powerReceiver, powerFilter);
    }

    private void stopReceiver() {
        wakeLock.release();
        if (pttKeyReceiver != null) {
            pttKeyReceiver.unbind();
            unregisterReceiver(pttKeyReceiver);
        }
//        if (powerReceiver != null) {
//            unregisterReceiver(powerReceiver);
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("确定要退出吗？")
                    .setCancelable(true)
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int id) {
                                    instruction.setPower(false);
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopReceiver();
    }
}
